import fs from 'fs'
import path from 'path'
import { app } from 'electron'
import Base from './base'
import mime from 'mime-types'
import logger from './logger'

/** 获取文件的DataUrl */
export const assetsDataUrl = (pathstr: string): string => {
  // 获取文件扩展名以确定MIME类型
  let extname = path.extname(pathstr).toLowerCase()
  if (extname.startsWith('.')) {
    extname = extname.slice(1) // 去除第一个字符
  }
  const mimeType = mime.lookup(extname)
  return `data:${mimeType};base64,${fs.readFileSync(pathstr).toString('base64')}`
}
/** 获取静态资源文件路径 */
export const resourcePath = (fnPath: string, superior: string = ''): string => {
  return 'wxmaster-resource://' + path.join(app.getAppPath(), 'resources', superior, fnPath)
}
// export const diyResourcePath = (diyPath: string): string => {
//   return 'wxmaster-resource://' + diyPath
// }

export const convertPath = (originalPath: string): string => {
  // 检测路径是否以斜杠开头，且之后是单个字母（盘符）跟着一个冒号
  const match = originalPath.match(/^\/([a-zA-Z])\/(.*)$/)
  if (match) {
    // 如果匹配，重构路径为 Windows 格式
    return `${match[1]}:/${match[2]}`
  } else {
    // 如果不匹配，返回原始路径
    return originalPath
  }
}
/** 本地保存base64格式数据 */
export const saveBase64 = (base64Str: string, outputPath: string, fn: string): Wx.Mawby.Request => {
  const result = Base.baseResult()
  try {
    let extension = ''
    const mimeMatch = base64Str.match(/^data:(image\/\w+);base64,/)
    // 确定文件格式
    if (mimeMatch) {
      const mimeType = mimeMatch[1]
      extension = mime.extension(mimeType) || ''
    }
    if (extension) {
      const base64Data = base64Str.replace(/^data:image\/\w+;base64,/, '')
      const imageBuffer = Buffer.from(base64Data, 'base64')
      const filePath = path.join(outputPath, fn + '.' + extension) // 文件路径
      fs.mkdirSync(path.dirname(filePath), { recursive: true }) // 确保目录存在
      fs.writeFileSync(filePath, imageBuffer) // 写入文件
      result.data = filePath
    } else {
      result.success = false
      result.msg = 'base64格式不正确'
    }
  } catch {
    result.success = false
    result.msg = '保存JSON数据失败'
  }
  return result
}
/** 保存JSON数据 */
export const saveJson = (data: Wx.Card.Data, outputPath: string, fn: string): Wx.Mawby.Request => {
  const result = Base.baseResult()
  try {
    fs.mkdirSync(outputPath, { recursive: true })
    const filePath = path.join(outputPath, fn)
    fs.writeFileSync(filePath, JSON.stringify(data, null, 2))
    logger.info('saveJson: ' + filePath)
    result.data = filePath
  } catch (e) {
    result.success = false
    result.msg = '保存JSON数据失败'
    logger.error('saveJsonError: ' + (e as Error).toString())
  }
  return result
}

/** 可读写资源路径 */
export const resourcePathStr = app.isPackaged ? path.join(process.resourcesPath, 'app.asar.unpacked', 'resources') : path.join(app.getAppPath(), 'resources')
